package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.configuration.CustomException;
import com.reggie.configuration.R;
import com.reggie.pojo.User;
import com.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 手机端登录
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody User user, HttpServletRequest request){

        //获取phone，判断phone，为空则抛出一个异常
        String phone = user.getPhone();
        if(phone == null){
            throw new CustomException("电话号码为空");
        }

        //在user表中查询
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone,user.getPhone());
        User one = userService.getOne(userLambdaQueryWrapper);

        //判断one是否为空
        if(one == null){
            throw new CustomException("该用户不存在");
        }

        //将用户id写入Session中
        request.getSession().setAttribute("user",one.getId());

        return R.success("登录成功");
    }
}
